package cn.wolfcode.p2p.base.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;


public class UserContext {
    public static final String USER_IN_SESSION = "loginInfo";
    public static final String VERIFY_CODE_IN_SESSION = "verify_code_in_session";

    private static HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    // 当前请求的ip
    private static String getCurrentRequestIp() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRemoteHost();
    }

    //获取当前请求的IP地址
    public static String getCurrentUserIp() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRemoteAddr();
    }

    public static void setCurrentUser(LoginInfo current) {
        if (current != null) {
            getSession().setAttribute(USER_IN_SESSION, current);
        } else {
            getSession().invalidate();
        }
    }

    public static LoginInfo getCurrentUser() {
        return (LoginInfo) getSession().getAttribute(USER_IN_SESSION);
    }

    //==========================================================================================
    //手机验证码
    public static void setVerifyCodeVO(VerifyCodeVO vo) {
        if (vo != null) {
            getSession().setAttribute(VERIFY_CODE_IN_SESSION, vo);
        } else {
            // 移除某一行,而不能用销毁
            getSession().removeAttribute(VERIFY_CODE_IN_SESSION);
        }
    }
    public  static VerifyCodeVO getVerifyCodeVO(){
        return (VerifyCodeVO) getSession().getAttribute(VERIFY_CODE_IN_SESSION);
    }


}
